package com.bbcare.comm;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.support.spring.FastJsonJsonView;
import com.bbcare.comm.BaseException;
import com.bbcare.comm.ErrorCode;
import com.bbcare.comm.ExceptionHandler;

public class ExceptionHandler implements HandlerExceptionResolver {

    private final Log logger = LogFactory.getLog(ExceptionHandler.class);

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
            Exception ex) {
        logger.error("error", ex);
        ModelAndView mv = new ModelAndView();
        FastJsonJsonView view = new FastJsonJsonView();
        Map<String, Object> attributes = new HashMap<String, Object>();
        attributes.put("success", false);
        if (ex instanceof JSONException) {
            attributes.put("code", ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR);
            attributes.put("msg", "入参格式错误，非json格式！");
        } else if (ex instanceof BaseException) {
            attributes.put("code", ((BaseException) ex).getErrId());
            attributes.put("msg", ((BaseException) ex).getErrMsg());
        } else if (ex instanceof DataAccessException) {
            attributes.put("code", 1000);
            attributes.put("msg", "操作数据资源异常，请联系系统管理员！");
        } else {
            attributes.put("code", 2000);
            attributes.put("msg", ex.getMessage());
        }
        view.setAttributesMap(attributes);
        mv.setView(view);
        return mv;
    }

}
